/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.is.city.routemanager;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JToggleButton;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.feature.FeatureCollections;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.map.FeatureLayer;
import org.geotools.referencing.crs.EPSGCRSAuthorityFactory;
import org.geotools.swing.JMapPane;
import org.geotools.swing.event.MapMouseEvent;
import org.geotools.swing.event.MapMouseListener;
import org.is.city.MyStyle;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CRSAuthorityFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;

/**
 *
 * @author oleg
 */
public class GuideMapPaneListener implements MapMouseListener {

    int clicks;
    DirectPosition2D points[];
    LinkedList<DirectPosition2D> pointsList;
    MultiPointGuideAction action;
    JMapPane pane;
    JToggleButton jToggleButton;
    String mode;

    public GuideMapPaneListener(MultiPointGuideAction action, JMapPane pane, JToggleButton jToggleButton, String mode) {
        if (mode == null ? "2" == null : mode.equals("2")) {
            points = new DirectPosition2D[2];
        } else if (mode == null ? "n" == null : mode.equals("n")) {
            pointsList = new LinkedList<DirectPosition2D>();
        }
        clicks = 0;
        this.pane = pane;
        this.action = action;
        this.jToggleButton = jToggleButton;
        this.mode = mode;
    }

    @Override
    public void onMouseClicked(MapMouseEvent ev) {
        if (mode == null ? "2" == null : mode.equals("2")) {
            points[clicks] = ev.getMapPosition();
        } else if (mode == null ? "n" == null : mode.equals("n")) {
            pointsList.add(ev.getMapPosition());
        }
        addTemporaryPoint(ev.getMapPosition(), clicks);
        clicks++;
        if ((clicks == 2) && (mode == null ? "2" == null : mode.equals("2"))) {
            for (int i = 0; i < clicks; i++) {
                //System.out.println("" + points[i]);
            }
            clicks = 0;
            jToggleButton.setSelected(false); //снимаем выделение с кнопки Guide
            action.addPoints(points);
            pane.removeMouseListener(this);
        }
    }

    @Override
    public void onMouseDragged(MapMouseEvent ev) {
    }

    @Override
    public void onMouseEntered(MapMouseEvent ev) {
    }

    @Override
    public void onMouseExited(MapMouseEvent ev) {
    }

    @Override
    public void onMouseMoved(MapMouseEvent ev) {
    }

    @Override
    public void onMousePressed(MapMouseEvent ev) {
    }

    @Override
    public void onMouseReleased(MapMouseEvent ev) {
    }

    @Override
    public void onMouseWheelMoved(MapMouseEvent ev) {
    }

    private void addTemporaryPoint(DirectPosition2D point, int point_number) {
        try {
            //Создаем слой точек назначения
            SimpleFeatureCollection pointsSFC = FeatureCollections.newCollection();
            SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
            b.setName("Route");
            b.add("name", String.class);
            CRSAuthorityFactory aDefault = EPSGCRSAuthorityFactory.getDefault();
            CoordinateReferenceSystem crs = aDefault.createCoordinateReferenceSystem("EPSG:32637");
            b.setCRS(crs);
            //add some geometry properties (first added is the default)
            b.add("destination", Point.class);
            b.setDefaultGeometry("destination");
            /*
             * почему-то сначала без attribute desciptor не рисовалось, а теперь все ок!?
            AttributeTypeBuilder build = new AttributeTypeBuilder();
            build.setNillable(true);
            build.setBinding(Point2D.class);
            AttributeDescriptor descriptor = build.buildDescriptor( "destination" );
            //b.add(descriptor);
             *
             */
            SimpleFeatureType buildFeatureType = b.buildFeatureType();

            SimpleFeatureBuilder builder = new SimpleFeatureBuilder(buildFeatureType);
            builder.add("point "+point_number);
            GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
            Coordinate coord = new Coordinate(point.x, point.y);
            Point p = geometryFactory.createPoint(coord);
            builder.add(p);
            SimpleFeature buildFeature = builder.buildFeature(null);
            pointsSFC.add(buildFeature);

            MyStyle ms = new MyStyle(MyStyle.GeomType.POINT);
            FeatureLayer pointsLayer = new FeatureLayer(pointsSFC, ms.createPointStyle(pointsSFC.getSchema().getGeometryDescriptor()), "temp");
            pane.getMapContext().addLayer(pointsLayer);
        } catch (NoSuchAuthorityCodeException ex) {
            Logger.getLogger(GuideMapPaneListener.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FactoryException ex) {
            Logger.getLogger(GuideMapPaneListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public DirectPosition2D[] getPoints() {
        Object[] toArray = pointsList.toArray();
        points=new DirectPosition2D[toArray.length];
        for(int i=0;i<toArray.length;++i){
            points[i]=(DirectPosition2D) toArray[i];
        }
        return points;
    }
}
